package com.MedDroid.task;

import android.os.AsyncTask;
import android.view.View;
import com.MedDroid.MainApp;
import com.MedDroid.activity.ViewProfileActivity;
import com.MedDroid.control.AuthenticationControl;
import com.MedDroid.control.DatabaseControl;
import com.MedDroid.entities.Permissions;
import com.MedDroid.entities.User;

import java.lang.ref.WeakReference;

/**
 * Created with IntelliJ IDEA.
 * User: Romen
 * Date: 02/12/13
 * Time: 3:21 PM
 * Description:
 */
public class LoadProfilePageTask extends AsyncTask<Integer, Void, User>
{
	AuthenticationControl AuthenticationC;
	DatabaseControl DatabaseC;
	WeakReference<ViewProfileActivity> ProfilePage;
	Permissions Access;

	public LoadProfilePageTask(AuthenticationControl Auth, DatabaseControl Data, ViewProfileActivity activity)
	{
		AuthenticationC = Auth;
		DatabaseC = Data;
		ProfilePage = new WeakReference<ViewProfileActivity>(activity);
	}

	@Override
	protected User doInBackground(Integer... integers)
	{
		Access = AuthenticationC.getAccess();
		return DatabaseC.findUser(User.UserIDStr,integers[0].toString());
	}

	@Override
	protected void onPostExecute(User user)
	{
		ViewProfileActivity Profile = ProfilePage.get();
		//Remove buttons
		if (!Access.getPermission(Permissions.PModifyUser) || AuthenticationC.getLoginUser().getUserID() == Profile.LoadedUser)
		{
			Profile.btnDeleteUser.setVisibility(View.GONE);
		}
		if (!Access.getPermission(Permissions.PModifyContact))
		{
			Profile.btnEditUser.setVisibility(View.GONE);
		}
		if (!Access.getPermission(Permissions.PViewMedical) && AuthenticationC.getLoginUser().getUserID() != Profile.LoadedUser)
		{
			Profile.btnViewMedical.setVisibility(View.GONE);
		}
		//Fill in fields
		if (user != null)
		{
			Profile.EditFirstName.setText(user.getFirstName());
			Profile.EditMiddleName.setText(user.getMiddleName());
			Profile.EditLastName.setText(user.getLastName());
			Profile.EditPhoneNumber.setText(user.getPhoneNumber());
			Profile.EditAddressLine.setText(user.getAddressLine());
			Profile.EditCity.setText(user.getCity());
			Profile.EditProvince.setText(user.getProvince());
			Profile.EditCountry.setText(user.getCountry());
			Profile.EditPostalCode.setText(user.getPostalCode());
			Profile.EditEmergencyFullName.setText(user.getEmergencyContact());
			Profile.EditEmergencyPhoneNumber.setText(user.getEmergencyPhoneNumber());
		}
		else
		{
			MainApp.log("Error loading user.");
		}
	}
}
